package de.hska.reka.websockets;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;
import org.xlightweb.IWebSocketConnection;
import org.xlightweb.TextMessage;

import de.hska.reka.websockets.Parser.JsonRPCParser;
import de.hska.reka.websockets.Parser.JsonRpcPackage;

@Component
public class OneToManyCallbackHandler implements ICallbackHandler {

	private List<IWebSocketConnection> webSocketConnections = new ArrayList<IWebSocketConnection>();
	private JsonRPCParser jsonRPCParser = new JsonRPCParser();

	public void addConnection(IWebSocketConnection connection) {
		this.webSocketConnections.add(connection);
	}

	public void removeConnection(IWebSocketConnection connection) {
		this.webSocketConnections.remove(connection);
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		JsonRpcPackage rpcPackage = new JsonRpcPackage();
		rpcPackage.setMethod(method.getDeclaringClass().getCanonicalName() + "."
				+ method.getName());
		rpcPackage.setParams(args);
		for (IWebSocketConnection connection : this.webSocketConnections) {
			connection.writeMessage(new TextMessage(this.jsonRPCParser
					.serialize(rpcPackage)));
		}
		return null;
	}

}
